package demo.sicua.votesystem.service.imp;

import demo.sicua.votesystem.constant.DataConstant;
import demo.sicua.votesystem.dao.AdminDao;
import demo.sicua.votesystem.entity.PO.AdminPO;
import demo.sicua.votesystem.entity.VO.ResultVO;
import demo.sicua.votesystem.service.AdminService;
import demo.sicua.votesystem.util.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class AdminServiceImp implements AdminService {

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private ResultVOUtil resultVOUtil;

    @Override
    public ResultVO loginAdmin(String username, String password, HttpServletRequest request) {
        if("".equals(username.trim()) && "".equals(password.trim())){
            // 用户传入的用户密码不能为空字符
            return resultVOUtil.paramError();
        }else {
            try{
                // 执行查询操作，可能抛出异常，所以需要try catch
                AdminPO adminPO = adminDao.selectAdminByPwdAndUsername(username,password);
                if (adminPO == null){
                    return resultVOUtil.resourceNotFound("您不是管理员");
                }else{
                    //存放用户凭据，存入session中
                    HttpSession session = request.getSession();
                    // 存放用户的id到会话session中，第一个参数是键，第二个参数是值
                    session.setAttribute(DataConstant.ADMIN_SESSION_NAME,adminPO.getId());
                    // 用户信息不为空，登录成功,返回凭据
                    return resultVOUtil.success("管理员登录成功");
                }
            }catch (Exception e){
                // 打印异常堆栈信息
                e.printStackTrace();
                // 一旦抛出异常就返回未知错误信息
                return resultVOUtil.unkwonError();
            }
        }
    }
}
